﻿#region 命名空间

using System;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web.Mvc;
using AutoMapper;
using Ext.Net;
using Ext.Net.MVC;
using Sharp.Application.Platform;
using Sharp.Domain.PlatformBoundedContext.MasterDataModule.Aggregates;
using Sharp.Domain.Repositories;
using Sharp.Infrastructure;
using Sharp.Infrastructure.IoC;
using Sharp.ServiceContracts;
using Sharp.Web.Models;
using PartialViewResult = Ext.Net.MVC.PartialViewResult;
#pragma warning disable 618

#endregion

namespace Sharp.Web.Controllers
{
    public class MasterDataController : Controller
    {
        // GET: Manage/MasterData
        public ActionResult Index(string containerId)
        {
            var model = new MasterDataIndexModel();
            model.LeftTree = new Node()
            {
                Text = ".",
                NodeID = "Root",
                Expanded = true,
                AutoDataBind = false,
                Checked = null
            };

            var builder = new TreeBuilder2<MasterData>
            {
                ChangeData = (p, treeNode) =>
                {
                    treeNode.Text = p.Name;
                    treeNode.NodeID = p.Id.ToString();
                    treeNode.Qtip = p.Code;
                    treeNode.CustomAttributes.Add(new ConfigItem() { Name = "FullName", Value = p.FullName });
                    treeNode.Expanded = true;
                }
            };



            var list = ServiceLocator.Instance.GetService<ISystemService>().GetMasterDataSort();

            builder.Build(list, model.LeftTree, null);

            return new PartialViewResult
            {
                Model = model,
                ContainerId = containerId,
                RenderMode = RenderMode.AddTo
            };
        }

        public ActionResult Create(string assemblyQualifiedName)
        {
            if (string.IsNullOrEmpty(assemblyQualifiedName))
            {
            }


            return new PartialViewResult { ViewName = "Edit", Model = new MasterDataModel() { AssemblyQualifiedName = assemblyQualifiedName } };
        }
        public ActionResult Edit(Guid? id, string assemblyQualifiedName)
        {
            if (string.IsNullOrEmpty(assemblyQualifiedName))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            object data = InitMethod(assemblyQualifiedName, "GetMasterDataInfo", new object[] { id });
            var dto = data.To<MasterDataModel>();
            object dropDown = InitMethod(assemblyQualifiedName, "GetMasterData", null);

            dto.DropDown = dropDown;

            return new PartialViewResult { ViewName = "Edit", Model = dto };
        }
        public ActionResult Details(Guid? id, string assemblyQualifiedName)
        {
            if (string.IsNullOrEmpty(assemblyQualifiedName))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            object data = InitMethod(assemblyQualifiedName, "GetMasterDataInfo", new object[] { id });
            var dto = data.To<MasterDataModel>();
            object dropDown = InitMethod(assemblyQualifiedName, "GetMasterData", null);

            dto.DropDown = dropDown;

            return new PartialViewResult { ViewName = "Edit", Model = dto };
        }
        [HttpPost]
        public ActionResult Save(MasterDataModel model)
        {
            string assemblyQualifiedName = model.AssemblyQualifiedName;
            var entityType = Type.GetType(assemblyQualifiedName);

            //if (!Mapper.GetAllTypeMaps().Any(x => x.SourceType == model.GetType() && x.DestinationType == entityType))
            //{
            //    Mapper.CreateMap(model.GetType(), entityType);
            //    Mapper.CreateMap(entityType, model.GetType());
            //}
            object newMasterData = Mapper.Map(model, model.GetType(), entityType);

            InitMethod(assemblyQualifiedName, "SaveMasterData", new object[] { newMasterData });

            return this.FormPanel();
        }

        #region 分页数据
        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ActionResult GetPaged(StoreRequestParameters parameters)
        {
            var assemblyQualifiedName = HttpContext.Request["assemblyQualifiedName"];


            dynamic obj = InitMethod(assemblyQualifiedName, "GetPaged", new object[] { parameters.Page, parameters.Limit });

            object data = obj.Data;
            int totalRecords = obj.TotalRecords;

            return this.Store(data, totalRecords);
        }
        #endregion

        [HttpPost]
        public JsonResult Delete(Guid[] ids)
        {
            var assemblyQualifiedName = HttpContext.Request["assemblyQualifiedName"];
            var res = new JsonResult();
            res.Data = InitMethod(assemblyQualifiedName, "DeleteMasterData", new object[] { ids });

            return res;
        }

        public object InitMethod(string assemblyQualifiedName, string methodName, object[] parameters)
        {
            Type ex = typeof(SystemServiceImpl);

            var context = ServiceLocator.Instance.GetService<IRepositoryContext>();
            var theObj = Activator.CreateInstance(ex, context);

            var genericMethod = Type.GetType(assemblyQualifiedName);
            MethodInfo mi = ex.GetMethod(methodName);
            MethodInfo gmi = mi.MakeGenericMethod(genericMethod);
            return gmi.Invoke(theObj, parameters);
        }
    }
}